package org.travel.app.common.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.travel.app.entity.IdVerification;
import java.io.IOException;

/**
 * @author nmm
 * @date 2024-12-2024/12/21
 * @deriction 身份证号验证工具类
 */

public class IDVerificationUtil {

    public  static IdVerification testIDVerification(IdVerification idVerification) {
        String url = "https://idenauthen.market.alicloudapi.com/idenAuthentication";
        // 获取appCode链接：https://market.console.aliyun.com/
        String appCode = "f25761b7aeff46a690b6da4b10828498";
//        String name = "蔡序俊";
//        String idNo = "360724200401125516";
        ObjectMapper objectMapper=new ObjectMapper();
        IdVerification idVerificationResult=null;
        try {
            idVerificationResult = objectMapper.readValue(postData(appCode, url, idVerification.getName(), idVerification.getIdNo()), IdVerification.class);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage());
        }
        return idVerificationResult;
    }

    public static String postData(String appCode, String url, String name, String idNo) throws IOException {
            String result = "";
            RequestBody formBody = new FormBody.Builder().add("name", name).add("idNo", idNo).build();
            Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(formBody).build();

            Call call = new OkHttpClient().newCall(request);
            Response response = null;
            try {
                response = call.execute();
            } catch (IOException e) {
                System.out.println("execute failed, message:" + e.getMessage());
            }

            assert response != null;
            if (!response.isSuccessful()) {
                // 当返回结果发生错误时
                // 状态码为403时一般是套餐包用尽，需续购；注意：续购不会改变秘钥（appCode），仅增加次数
                // 续购链接：https://market.aliyun.com/products/57000002/cmapi025518.html
                System.out.println("request failed----" + "返回状态码" + response.code()  + ",message:" + response.message());
            }
            result = response.body().string();

            return result;
    }
}